package com.pengjunlee.hive.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.pengjunlee.hive.bean.VehicleCache;
import com.pengjunlee.hive.utils.JedisUtils;

import redis.clients.jedis.Jedis;


@Service
public class QuartzService implements EnvironmentAware {
	
	private Jedis jedis;
	
	@SuppressWarnings("unused")
	@Autowired
	private Environment env;
	
	@Override
	public void setEnvironment(Environment env) {
		this.env = env;
	}
	
	/**
	 * 根据设备号获取设备最新实时状态
	 * @param terminalCodes
	 * @return
	 * @throws Exception 
	 * @throws InterruptedException
	 */
	public List<VehicleCache> queryH5VehicleInfoByTerminalCode(String terminalCodes) throws Exception {
		List<VehicleCache> list = new ArrayList<VehicleCache>();
		//判断设备号是否为空
		if(StringUtils.isBlank(terminalCodes)){
			throw new Exception("请输入设备号!");
		}
		
		//解析设备号字符串
		String[] terminalCodeArray = terminalCodes.split(",");
		if(terminalCodeArray != null && terminalCodeArray.length > 0){
			Set<String> sets = null;
			//redis初始化
			jedis = JedisUtils.getResource(env.getProperty("spring.redis.host"), 
					Integer.parseInt(env.getProperty("spring.redis.port")), env.getProperty("spring.redis.password"));
			
			for(int index=0; index<terminalCodeArray.length; index++){
				//获取redis中所有的所有的key值
				if(sets == null){
					jedis.select(1);
					sets = jedis.hkeys("YDCX_TM30_EHS3_STATUS_OFFSET");
				}
				
				//车辆时间戳列表
				List<Long> lastRefreshTimeList = new ArrayList<Long>();
				
				for(String str : sets){
					String tc = str.split("-")[0];
					String tcTime = str.split("-")[1];
					if(tc.equals(terminalCodeArray[index])){
						lastRefreshTimeList.add(Long.parseLong(tcTime));
					}
				}
				//时间戳列表排序
				if(lastRefreshTimeList != null && lastRefreshTimeList.size() > 0){
					Collections.sort(lastRefreshTimeList);
				}
				
				if(lastRefreshTimeList != null && lastRefreshTimeList.size() > 0){
					for(int i=lastRefreshTimeList.size()-1; i>=0; i--){
						Long finalTime = lastRefreshTimeList.get(i);
						String hkey = terminalCodeArray[index] + "-" + finalTime.toString();
						jedis.select(1);
						String value = jedis.hget("YDCX_TM30_EHS3_STATUS_OFFSET", hkey);
						if(StringUtils.isBlank(value) || value.equals("{}")){
							continue;
						}else{
							VehicleCache vc = new VehicleCache();
							vc.setTerminalCode(terminalCodeArray[index]);
							vc.setValue(value);
							list.add(vc);
						}
					}
				}
			}
			
			//释放资源
			JedisUtils.returnResource(jedis);
		}
		
        return list;
	}
	
	/**
	 * 更新缓存中的数据
	 * @throws Exception 
	 */
	public void updateVehicleFromCache() throws Exception{
		List<VehicleCache> list = new ArrayList<VehicleCache>(); 
		//redis初始化
		jedis = JedisUtils.getResource(env.getProperty("spring.redis.host"), 
				Integer.parseInt(env.getProperty("spring.redis.port")), env.getProperty("spring.redis.password"));
		jedis.select(0);
		
		//获取注册缓存列表数据
		Set<String> set = jedis.hkeys("tm30_status_ehs3_vin_value_cache");
		//获取注册缓存列表数据
		Set<String> timesSet = jedis.hkeys("tm30_status_ehs3_vin_timestamp_cache");
		if(set != null && set.size() > 0){
			list = queryH5VehicleInfoByTerminalCode(set.toString());
			if(list != null && list.size() > 0){
				for(VehicleCache vc : list){
					//删除实时信息缓存
					jedis.hdel("tm30_status_ehs3_vin_value_cache", vc.getTerminalCode());
					//删除实时时间戳缓存
					jedis.hdel("tm30_status_ehs3_vin_timestamp_cache", vc.getTerminalCode());
					//新增实时信息
					jedis.hset("tm30_status_ehs3_vin_value_cache", vc.getTerminalCode(), vc.getTerminalCode());
			 		//新增时间戳缓存
					jedis.hset("tm30_status_ehs3_vin_timestamp_cache", vc.getTerminalCode(), vc.getLastRefreshTime());
				}
			}
		}
		//释放资源
		JedisUtils.returnResource(jedis);
	}
			
	// 每隔10s更新一次缓存表
	/*@Scheduled(fixedRate = 10000) 
    public void circleExecuteCache() throws Exception{
		updateVehicleFromCache();
	}*/
}